

import java.rmi.ConnectException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class TTTRmiImpl extends UnicastRemoteObject implements TTTRmi {
	
	private TicTacToeGui gui;
	private char opponentMark;
	private boolean isServer;
	private String rmiUrl;
	
	protected TTTRmiImpl(TicTacToeGui gui) throws RemoteException {
		this.gui = gui;
		this.opponentMark = 'X';
		this.isServer = false;
	}

	/**
	 * Kobler til server
	 */
	@Override
	public String connect(String name, char mark, TTTRmi opponent)
			throws RemoteException {
		try {
			Naming.unbind(rmiUrl);
		} catch (NotBoundException nex) {
			gui.println("Fant ingen bundne RMI-registre...");
		} catch (Exception e) {
			gui.println("En feil oppstod: " + e.getMessage());
		}
		isServer = false;
		opponentMark = mark;
		gui.setOpponent(opponent);
		return gui.getPlayerName();
	}

	/**
	 * Merk motstanderens rute der det ble satt merke
	 */
	@Override
	public void mark(int x, int y) throws RemoteException {
		gui.println("Motstanderen valgte (" + x + ", " + y + ")...");
		gui.setMark(x, y, opponentMark);
		gui.setMyTurn(true);
	}

	/**
	 * Start et nytt spill
	 */
	@Override
	public void reset() throws RemoteException {
		gui.println("Motstanderen ønsker å starte runden på nytt...");
		gui.clearBoard();
		gui.setMyTurn(opponentMark == 'X' ? false : true);
	}

	/**
	 * Motstander har koblet fra
	 */
	@Override
	public void disconnect() throws RemoteException {
		gui.println("Motstanderen koblet fra...");
		gui.setOpponent(null);
	}

	/**
	 * Erkjenne tapet :-(
	 */
	@Override
	public void notifyVictory() throws RemoteException {
		gui.setMyTurn(false);
		gui.println("Game over! Motstanderen har vunnet!");
	}
	
	/**
	 * Opprette server og binde RMI-objektet
	 * @param rmiUrl
	 */
	public void bind(String rmiUrl) {
		// Start RMI registry
		try {
			java.rmi.registry.LocateRegistry.createRegistry(gui.PORT);
		} catch (Exception e) {
			
		}
		this.rmiUrl = rmiUrl;
		
		// Bind this object to a RMI register
		try {
			Naming.rebind(rmiUrl, this);
			gui.println("Venter på spiller...");
		} catch (ConnectException cex) {
			gui.println("Fant ikke RMI-register på " + rmiUrl + "...");
		} catch (Exception e) {
			gui.println("En feil oppstod: " + e.getMessage());
		}
		isServer = true;
	}
	
	public boolean isServer() {
		return isServer;
	}
	
	public String getURL() {
		return rmiUrl;
	}

}
